# -*- coding: utf-8 -*-
# frontend/utils/api_client.py
import requests
import json
import streamlit as st
from typing import Dict, List, Optional

class APIClient:
    def __init__(self, base_url: str = "http://localhost:8080"):
        self.base_url = base_url
        self.session = requests.Session()
    
    def create_session(self, user_id: str) -> Dict:
        """创建新的聊天会话"""
        try:
            response = self.session.post(
                f"{self.base_url}/api/v1/sessions",
                json={"user_id": user_id},
                timeout=10
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"❌ 创建会话失败: {str(e)}")
            return {}
    
    def send_message(self, session_id: str, message_content: str, message_format: str = "plaintext") -> Dict:
        """发送消息"""
        try:
            response = self.session.post(
                f"{self.base_url}/api/v1/messages",
                json={
                    "session_id": session_id,
                    "message_content": message_content,
                    "message_format": message_format
                },
                timeout=30
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"❌ 发送消息失败: {str(e)}")
            return {}
    
    def invoke_model(self, model_id: str, session_id: str, message_content: str) -> Dict:
        """调用特定模型"""
        try:
            response = self.session.post(
                f"{self.base_url}/api/v1/models/{model_id}/invoke",
                json={
                    "session_id": session_id,
                    "message_content": message_content
                },
                timeout=60
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"❌ 调用模型失败: {str(e)}")
            return {}
    
    def get_performance_metrics(self) -> Dict:
        """获取性能指标"""
        try:
            response = self.session.get(f"{self.base_url}/api/v1/performance/metrics")
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"❌ 获取性能指标失败: {str(e)}")
            return {}
